package com.jjrwa.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public abstract class FreemarkerUtils {

    public static <T> String processJavaCode(String templateName, T data) {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
        configuration.setClassForTemplateLoading(FreemarkerUtils.class, "/");
        Template template = null;
        try {
            template = configuration.getTemplate(templateName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("获取模板异常[" + templateName + "]");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("data", data);
        StringWriter sw = new StringWriter();
        try {
            template.process(param, sw);
            String result = sw.toString();
            //mac
            result = result.replace("\r", "");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取模板解析异常[" + templateName + "]");
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
